package offer;

import java.util.*;

public class offer32three {
}
class Solution323 {
    public static List<List<Integer>> levelOrder(TreeNode root) {
//        思路：先层序遍历二叉树，如果是偶数层，则将其放入队列中
//        如果是奇数层则放入栈中
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        int count = 0;
        queue.add(root);
        int len = queue.size();
        if (root == null) {
            return new ArrayList<>();
        }
        while (!queue.isEmpty() ) {
            List<Integer> track = new ArrayList<>();
            if (!queue.isEmpty()) {
                if (count % 2 == 0) {
                    for (int i = 0; i < len; i++) {
                        TreeNode temp = queue.poll();
                        track.add(temp.val);
                        if (temp.left != null) queue.add(temp.left);
                        if (temp.right != null) queue.add(temp.right);
                    }
                    if (!track.isEmpty()) res.add(track);
                    count++;
                    len = queue.size();
                } else {
                    Collections.reverse((List<?>) queue);
                    for (int i = 0; i < len; i++) {
                        TreeNode temp = queue.poll();
                        track.add(temp.val);
                        if (temp.left != null) queue.add(temp.left);
                        if (temp.right != null) queue.add(temp.right);
                    }
                    if (!track.isEmpty()) res.add(track);
                    count++;
                    len =queue.size();
                    Collections.reverse((List<?>) queue);
                }

            }
        }


            return res;
        }
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        TreeNode node3 = new TreeNode(5);
        TreeNode node4 = new TreeNode(4);
        root.left = node1;
        root.right=  node2;
        node2.right = node3;
        node1.left = node4;
       levelOrder(root);

    }
    }
